package cn.rayfoo.common.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author rayfoo@qq.com
 * @version 1.0
 * <p>解决跨域问题</p>
 * @date 2020/8/17 10:58
 */
@WebFilter(filterName = "cors",urlPatterns = "/*")
public class HeadersCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        /**
         * 指定允许其他域名访问
         * 一般用法（*，指定域，动态设置），3是因为*不允许携带认证头和cookies
         */
        response.setHeader("Access-Control-Allow-Origin", "*");

        /**
         * 该次的请求方式
         */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

        /**
         * 预检结果缓存时间,也就是上面说到的缓存啦
         */
        response.setHeader("Access-Control-Max-Age" , "3600" );

        /**
         * 允许的请求头字段
         */
        response.setHeader("Access-Control-Allow-Headers" , "x-requested-with,Content-Type,Authorization,Content-Disposition,content-Type" );

        /**
         * 允许cookie跨域
         */
        response.setHeader("Access-Control-Allow-Credentials" , "true" );

        /**
         * 放行请求
         */
        chain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}